use std::collections::HashMap;
use std::sync::atomic::AtomicU64;
use std::sync::Arc;
use parking_lot::Mutex;
use crate::common::Chunk;
use crate::container::ContainerId;

pub struct DedupWorkFlow {
    map:Mutex<HashMap<Vec<u8>, Arc<AtomicU64>>>,
}

impl DedupWorkFlow {
    pub fn new() -> Self {
        Self { map:Mutex::new(HashMap::new()) }
    }
    
    pub fn find_and_insert(&self, chunk:&Chunk) -> Option<Arc<AtomicU64>> {
        let mut map = self.map.lock();
        let result = map.get(chunk.fp()).cloned();
        if result.is_none() {
            let container_id = Arc::new(AtomicU64::new(0));
            map.insert(chunk.fp().to_vec(), container_id);
        }
        result
    }

    pub fn delete_with_set(&self, fp:&[u8], container_id:ContainerId) {
        let container_id_pointer = self.map.lock().remove(fp);
        if let Some(p) = container_id_pointer {
            p.store(container_id, std::sync::atomic::Ordering::SeqCst);
        }
    }
}